package org.mojo.plugin.tibco.designer;

/*
 * Copyright 2001-2005 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;


import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;

/**
 * Tibco Generate TIBCO Designer5.pref the tibco preferences file
 * 
 * @author Corentin Lonfils
 * 
 * @aggregator
 * @goal tibco
 */
public class TibcoDesigner extends AbstractMojo {


	/**
	 * @parameter expression="${project}"
	 * @required
	 * @readonly
	 */
	private MavenProject project;

	


	public void execute() throws MojoExecutionException, MojoFailureException {
		if (!project.getPackaging().equals("pom")){
			return;
		}

		File parentFile = project.getBasedir();
		File[] tibcoDirectoryConfig = parentFile.listFiles(new FileFilter() {

			public boolean accept(File file) {
				if (file.getAbsolutePath().endsWith(".TIBCO") && file.isDirectory()){
					return true;
				}
				return false;
			}
		});
		if (tibcoDirectoryConfig.length < 0 && tibcoDirectoryConfig.length != 1){
			throw new RuntimeException("The tibco Directory Config is not correctly setuped");
		}
		File rootProjectFolder = tibcoDirectoryConfig[0];
		File[] designConfigFile = (rootProjectFolder.listFiles(new FilenameFilter() {
			public boolean accept(File dir, String name) {
				if (name.equals("Designer5.prefs")){
					return true;
				}
				return false;
			}
		}));
		updateDesignerPref(designConfigFile[0], parentFile);
	}


	private void updateDesignerPref(File configFile, File parentFile){
		try {
			InputStream bf;
			File tempConfig = new File(configFile.getAbsolutePath()+".temp");
			FileOutputStream outStream = new FileOutputStream(tempConfig, false);
			Writer out = new OutputStreamWriter(outStream);
			BufferedWriter writer = new BufferedWriter(out);

			bf = new FileInputStream(configFile);
			BufferedReader reader = new BufferedReader(new InputStreamReader(bf));
			String line;
			while ((line = reader.readLine()) != null){
				if (line.startsWith("user.palette.dir") || !line.startsWith("filealias.pref.") || ! line.startsWith("ae.recent.projects.") || line.startsWith( "fs.vfilestore.last.dir.pref")){
					writer.write(line + "\r\n");
				}
			}

			updateConfig(writer, parentFile);

			writer.flush();
			writer.close();
			reader.close();

			//Delete previous config and update the new one.
			String getPath = configFile.getAbsolutePath();
			configFile.delete();
			copy(new FileInputStream(tempConfig), new FileOutputStream(getPath));
			tempConfig.delete();

		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}


	private void updateConfig(BufferedWriter writer, File parentFile) throws IOException {
		//TODO Hardcoded Projlib folder (will move to maven repo dependencies)
		File projLibFolder = new File(parentFile, "Projlib");
		// TODO CustomPalette location should configurable
		File customePaletteFolder = new File(parentFile, "CustomPalette");
		String[] result = projLibFolder.list();
		for (int i = 0; i < result.length; i++) {
			String projLib = result[i];
			if (projLib.endsWith(".projlib")){
				writer.write("filealias.pref."+i+"="+projLib+"\\="+projLibFolder.getPath().replaceAll("\\\\", "/") +"/"+ projLib);
				writer.write("\r\n");
			}
		}
		writer.write("user.palette.dir="+ customePaletteFolder.getPath().replaceAll("\\\\", "/"));
		writer.write("\r\n");

		@SuppressWarnings("unchecked")
		List<String> modules = project.getModules();
		for (int i = 0; i < modules.size(); i++) {
			String module = modules.get(i);
			writer.write("ae.recent.projects."+i+"=projectName\\="+module+"&rootDirectory\\="+parentFile.getPath().replaceAll("\\\\", "/")+"\\\\"+module);
			writer.write("\r\n");
		}
	}

	private void copy(FileInputStream fis, FileOutputStream fos){
		try {
			byte[] readData = new byte[1024];
			int i = fis.read(readData);

			while (i != -1) {
				fos.write(readData, 0, i);
				i = fis.read(readData);
			}
			fis.close();
			fos.close();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}


}
